package com.sunyard.manage.listenster;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.sunyard.dal.entity.Lock;
import com.sunyard.manage.service.LockService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * @author: ZhangShuai
 * @description:
 * @create: 2022-07-06 15:47
 **/
@Slf4j
public class ExcelLister extends AnalysisEventListener<Lock> {
    private static final int BATCH_COUNT = 500;
    List<Lock> list = new ArrayList<>();

    public LockService lockService;

    public ExcelLister() {
    }

    public ExcelLister(LockService lockService) {
        this.lockService = lockService;
    }

    //读取excel的内容  一行行进行读取   头部那行自动舍去
    @Override
    public void invoke(Lock lock, AnalysisContext analysisContext) {
        log.info("解析到一条数据:{}", JSON.toJSONString(lock));
        if (lock == null) {
            throw new RuntimeException("文件数据异常");
        }
        Lock reserExcel = new Lock();
        reserExcel.setLockName(lock.getLockName());
        reserExcel.setOrgId(lock.getOrgId());
        reserExcel.setLockSn(lock.getLockSn());
        reserExcel.setMissionType(lock.getMissionType());
        reserExcel.setLockType(lock.getLockType());
        reserExcel.setIsCheck(lock.getIsCheck());
        reserExcel.setReversion(lock.getReversion());
        reserExcel.setCreateTime(lock.getCreateTime());
        reserExcel.setRemark(lock.getRemark());
        list.add(reserExcel);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            // 存储完成清理 list
            list.clear();
        }


    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        list.remove(0);
        lockService.addLocksList(list);
        log.info("存储数据库成功！");
    }
}
